package net.zhengxinyun.performance.App.appCtrl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.App.dto.DepartIndexDataDTO;
import net.zhengxinyun.performance.App.dto.IndexDTOs.DepatIndexDTO;
import net.zhengxinyun.performance.App.dto.IndexUserDTO;
import net.zhengxinyun.performance.App.service.deptIndex.DeptIndexService;
import net.zhengxinyun.performance.Util.DataUtil;
import net.zhengxinyun.performance.Util.DateUtils;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.data.UserAppDTO;
import net.zhengxinyun.performance.entity.CountryUnitIndicatorsEntity;
import net.zhengxinyun.performance.entity.CountryUnitScoreEntity;
import net.zhengxinyun.performance.entity.DepartmentEntity;
import net.zhengxinyun.performance.entity.UserEntity;
import net.zhengxinyun.performance.filter.CountryUnitIndicatorsFilter;
import net.zhengxinyun.performance.filter.CountryUnitScoreFilter;
import net.zhengxinyun.performance.filter.TownIndicatorsFilter;
import net.zhengxinyun.performance.filter.UserFilter;
import net.zhengxinyun.performance.service.department.DepartmentService;
import net.zhengxinyun.performance.service.indicators.CountryUnitIndicatorsService;
import net.zhengxinyun.performance.service.indicators.CountryUnitScoreService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 县直单位指标考核 接口
 */
@RestController
@RequestMapping("/app/countryDept/")
public class DeptIndexCtrl extends BaseCtrl {

    @Autowired
    private DeptIndexService deptIndexService;
    @Autowired
    private CountryUnitIndicatorsService webDeptIndService;
    @Autowired
    private CountryUnitScoreService countryUnitScoreService;
    @Autowired
    private DepartmentService departmentService;




    //县直单位
    @PostMapping("/deptIndexs")
    public Result<HashMap<String,Object>> deprtIndex(@RequestBody IndexUserDTO filter)
    {

        CountryUnitScoreFilter deptfilter = new CountryUnitScoreFilter();
        BeanUtils.copyProperties(filter,deptfilter);
        String currentYear = getCurrentYear();
        if(StringUtils.isBlank(filter.getUserPhone()))
        {
            return ResultUtils.getResults(Result.Status.ERROR, "手机号为空",null);
        }
        if(StringUtils.isBlank(deptfilter.getDateTime()))
        {
            deptfilter.setDateTime(DateUtils.getLastMonth(currentYear));
        }
        UserFilter user = getUserInfo(filter.getUserPhone());
        String datetime  = deptfilter.getDateTime();
        List<CountryUnitScoreFilter> deptIndexs = deptIndexService.getDeptIndexs(deptfilter, user);
        deptIndexs.forEach(filter1 -> filter1.setDateTime(datetime));
        HashMap<String,Object> map = new HashMap<>();
        map.put("data",deptIndexs);
        System.out.println("------接口： /deptIndexs");
        return ResultUtils.getResults(Result.Status.SUCCESS, "获取县直单位数据", map);
    }
    // 县直单位数据二级页面 分数页
    @PostMapping("/deptScoreSecond")
    public Result<HashMap<String,Object>> deptScoreSecond(@RequestBody IndexUserDTO filter)
    {

        String currentYear = getCurrentYear();
        HashMap<String,Object> map = new HashMap<>();
        if(ObjectUtils.isBlank(filter.getIndexId()))
        {
            return  ResultUtils.getResults(Result.Status.ERROR,"指标Id为空，请重试",null);

        }
        if(StringUtils.isBlank(filter.getDateTime()))
        {
            filter.setDateTime(DateUtils.getLastMonth(currentYear));
        }
        List<DepartIndexDataDTO> list = deptIndexService.getSingleIndexScore(filter.getIndexId(), filter.getDateTime());

        map.put("data",list);
        System.out.println("------接口： /deptScoreSecond");
        return ResultUtils.getResults(Result.Status.SUCCESS, "获取县直单位考核数据成功", map);
    }

  /*  // 县直单位数据三级页面 分数页
    @PostMapping("/deptScoreThree")
    public Result<HashMap<String,Object>> deptScoreThree(@RequestBody IndexUserDTO filter)
    {
        HashMap<String,Object> map = new HashMap<>();
        if(ObjectUtils.isBlank(filter.getIndexId())||StringUtils.isBlank(filter.getDepartcode())  )
        {
            return  ResultUtils.getResults(Result.Status.ERROR,"参数indexId或者departcode为空，沙雕，请重试",null);
        }
        List<DepartIndexDataDTO> departIndexDataDTOS = deptIndexService.IndexWholeScore(filter.getIndexId(), filter.getDepartcode());
        map.put("data",departIndexDataDTOS);

        return ResultUtils.getResults(Result.Status.SUCCESS, "获取县直单位考核数据成功", map);
    }*/

  //app县直单位指标管理 获取所有县直单位指标：
    @PostMapping("/deptManage")
    public Result<HashMap<String,Object>> getdeptIndexs(@RequestBody UserAppDTO   param)
    {
        String tel = param.getUserPhone();

        UserFilter userInfo = getUserInfo(tel);

        CountryUnitIndicatorsFilter filter = new CountryUnitIndicatorsFilter();
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userInfo,userEntity);

        List<CountryUnitIndicatorsEntity> query = webDeptIndService.query(filter, userEntity);


        HashMap<String,Object> dataMap = new HashMap<>();

        dataMap.put("data",query);
        System.out.println("/deptManage");
        return ResultUtils.getSuccessResults(dataMap);


    }


    //指标操作： 增删改
    @PostMapping("/editdeptIndex")
    public Result editDeptIndex(@RequestBody DepatIndexDTO param)
    {

        String tel = param.getUserPhone();
        UserFilter userInfo = getUserInfo(tel);

        String leadUnit = param.getLeadUnit();
        String dateTime = param.getDateTime();
        String indexName = param.getIndexName();
        if(StringUtils.isBlank(leadUnit)||StringUtils.isBlank(dateTime)||StringUtils.isBlank(indexName))
        {
            return  ResultUtils.getResults(Result.Status.ERROR,"参数indexName,leadUnit编码和dateTime不能为空");
        }
        CountryUnitIndicatorsEntity entity = new CountryUnitIndicatorsEntity();
        entity.setId(null);
        entity.setIndexName(indexName);
        entity.setLeadUnit(leadUnit);
        entity.setDateTime(dateTime);

        String optionType = param.getOptionType();
        switch (optionType)
        {
            case "add":
                int insert = webDeptIndService.insert(entity);
                if(insert==0){
                    return  ResultUtils.getResults(Result.Status.ERROR,"无数据更新");
                }
                break;
            case "update":
                if(ObjectUtils.isBlank(param.getId()))
                {
                    return  ResultUtils.getResults(Result.Status.ERROR,"修改操作时候 参数id不能为空");

                }
                entity.setId(param.getId());
                int update = webDeptIndService.update(entity);
                if(update==0){
                    return  ResultUtils.getResults(Result.Status.ERROR,"无数据更新");
                }
                break;
            case "del":
                if(ObjectUtils.isBlank(param.getId()))
                {
                    return  ResultUtils.getResults(Result.Status.ERROR,"修改操作时候 参数id不能为空");
                }
                entity.setId(param.getId());
                String delete = webDeptIndService.delete(entity);
                if(!"删除成功".equals(delete)){
                    return  ResultUtils.getResults(Result.Status.ERROR,"无数据更新");
                }
        }
        System.out.println("/editdeptIndex");
        return  ResultUtils.getSuccessResults("操作成功");
    }


    //指标获取所有指标填写状态
    @PostMapping("/getIndexScore")
    public Result<HashMap<String, Object>> getIndexScore(@RequestBody DepatIndexDTO param)
    {

        String currentYear = getCurrentYear();
        //if(ObjectUtils.is)
        String tel = param.getUserPhone();
        UserFilter userInfo = getUserInfo(tel);

        CountryUnitScoreFilter filter = new CountryUnitScoreFilter();
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userInfo,userEntity);
        if(StringUtils.isBlank(param.getDateTime())){
            filter.setDateTime(DateUtils.getLastMonth(currentYear));
        }

        List<CountryUnitScoreFilter> scorelists = countryUnitScoreService.queryScoreHomeDate(filter, userEntity);

        HashMap<String,Object> datamap = new HashMap<>();
        datamap.put("data",scorelists);
        datamap.put("dateTime",filter.getDateTime());
        System.out.println("/getIndexScore");
        return ResultUtils.getSuccessResults(datamap);

    }
    //分数列表
    @PostMapping("/deptScore")
    public Result<HashMap<String,Object>> getdeptScore(@RequestBody DepatIndexDTO param)
    {

        Long id = param.getId();
        String dateTime = param.getDateTime();

        if(ObjectUtils.isBlank(id))
        {
            return  ResultUtils.getResults(Result.Status.ERROR,"参数indexName,leadUnit编码和dateTime不能为空",null);
        }
        if(StringUtils.isBlank(dateTime))
        {
            dateTime= DateUtils.getLastMonth(getCurrentYear());
        }

        List<CountryUnitScoreFilter> scorelists = countryUnitScoreService.getdeptScore(id, dateTime);

        if(ObjectUtils.isBlank(scorelists))
        {
            List<DepartmentEntity> depts = departmentService.selectForDepartment(null, "县直单位");


            scorelists= new ArrayList<>();

            for (DepartmentEntity dept : depts) {
                CountryUnitScoreFilter dto = new CountryUnitScoreFilter();

                dto.setIndexId(id+"");
                dto.setDepartCode(dept.getDepartcode());
                dto.setDepartment(dept.getDepartAddr());
                scorelists.add(dto);

            }


        }

        HashMap<String,Object> datamap = new HashMap<>();
        datamap.put("data",scorelists);
        System.out.println("/deptScore");
        return  ResultUtils.getSuccessResults(datamap);

    }

    @PostMapping("/editDeptScore")
    public Result<String> editDeptScore(@RequestBody DepatIndexDTO param)
    {
        String StringScore = param.getListScore();
        if(StringUtils.isBlank(StringScore)){
            return  ResultUtils.getResults(Result.Status.ERROR,"数组listScore 不能为空",null);

        }

        List<CountryUnitScoreEntity> listScore = new ArrayList<>();

        JSONArray array = JSONArray.parseArray(StringScore);
        for (int i = array.size() - 1; i >= 0; i--) {
            JSONObject scoreObj = array.getJSONObject(i);
            CountryUnitScoreEntity dto = scoreObj.toJavaObject(CountryUnitScoreEntity.class);
            listScore.add(dto);

        }


        Long id = param.getId();
        //String s = countryUnitScoreService.saveImportUnitScore(listScore, id);

        String s = deptIndexService.saveDeptScores(listScore, id);
        if(!"ok".equals(s)){
            return ResultUtils.getResults(Result.Status.ERROR,s);
        }
        System.out.println("/editDeptScore");
        return ResultUtils.getSuccessResults("操作成功");

    }






}
